package com.example.demo.keyresolver.impl;

import cn.hutool.crypto.SecureUtil;
import com.example.demo.annotation.Idempotent;
import com.example.demo.keyresolver.IdempotentKeyResolver;
import com.example.demo.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 默认幂等 Key 解析器，使用方法名 + 方法参数，组装成一个 Key
 * <p>
 * 为了避免 Key 过长，使用 MD5 进行“压缩”
 *
 * @author houp
 */
@Component
@Slf4j
public class DefaultIdempotentKeyResolver implements IdempotentKeyResolver {

    @Override
    public String resolver(HttpServletRequest request, JoinPoint joinPoint, Idempotent idempotent) {
        StringBuilder data = new StringBuilder();
        data.append(joinPoint.getSignature().toString());
        data.append(":");
        data.append(request.getMethod());
        data.append(":");
        data.append(JsonUtils.toJson(joinPoint.getArgs()));
        // String argsStr = StrUtil.join(",", joinPoint.getArgs());
        log.info("md5加密前数据: " + JsonUtils.toJson(data.toString()));
        String md5 = SecureUtil.md5(data.toString());
        return md5;
    }

}
